// 获取页面元素
const inputText = document.getElementById('varArea');
const submitBtn = document.getElementById('submitBtn');
const feedbackBtn = document.getElementById('feedbackBtn');
const markdownOutput = document.getElementById('markdownOutput');
const urlParams = new URLSearchParams(window.location.search);
const patientID = urlParams.has('patientID') ? urlParams.get('patientID') : "test";
const generateUrl = window.config.backendapiUrl+'/generate';
const feedbackUrl = window.config.backendapiUrl+'/feedback';
// 患者id前端显示
document.getElementById('patientID').textContent = patientID
// 按钮点击事件
submitBtn.addEventListener('click', async () => {
    const text = inputText.value.trim();
    if (!text) {
        alert('请输入一些文本！');
        return;
    }

    // 禁用按钮，避免重复点击
    submitBtn.disabled = true;
    markdownOutput.innerHTML = ''; // 清空之前的内容

    try {
        const response = await fetch(generateUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ text: text }),
        });

        if (!response.ok) {
            throw new Error('请求失败');
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let done = false;
        let markdownText = '';

        while (!done) {
            const { value, done: readerDone } = await reader.read();
            done = readerDone;
            markdownText += decoder.decode(value, { stream: true });
            markdownOutput.innerHTML = window.marked.parse(markdownText); // 使用 marked.js 解析 Markdown
        }
    } catch (error) {
        console.error('发生错误：', error);
        alert('请求数据失败，请重试！');
    }

    // 恢复按钮状态
    submitBtn.disabled = false;
    feedbackBtn.disabled = false;
});
// 获取可编辑的内容元素和提交按钮
const feedbackButton = document.getElementById('feedbackBtn');
const id = document.getElementById('patientID').textContent

feedbackButton.addEventListener('click', async (event) => {
    event.preventDefault(); // 防止默认行为
    event.stopPropagation(); // 防止事件冒泡
    let allContent = {}
    let items = document.querySelectorAll('.item');
    // 遍历每个 p.item 元素
    items.forEach(item => {
        // 获取 strong 元素的文本内容
        let title = item.querySelector('strong') ? item.querySelector('strong').textContent : '';

        // 获取 span 元素的 title 属性内容
        let hint = item.querySelector('span') ? item.querySelector('span').getAttribute('title') : '';

        // 获取 editable-content 元素的内容
        let content = item.querySelector('.editable-content') ? item.querySelector('.editable-content').textContent : '';
        let originContent = item.querySelector('.editable-content') ? item.querySelector('.editable-content').getAttribute("data-original-content") : '';
        // 组成三元组
        let data = {
            hint: hint,
            content: content,
            origin: originContent
        };
        debugger
        allContent[title] = data;
        allContent["input"] = inputText.value.trim();
    });
    await sendFeedback(patientID, allContent);
});

async function sendFeedback(id, content) {
    const requestData = {
        text: { [id]: content }
    };
    debugger
    try {
        const response = await fetch(feedbackUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        });

        if (!response.ok) {
            throw new Error(`Server responded with status: ${response.status}`);
        }
    } catch (error) {
        console.error('Error in sendFeedback:', error);
        throw error;
    }
}